#include"Protocol.hpp"
#include"Sock.hpp"

#include<iostream>
#include<unistd.h>
using namespace bobo;

void usage(const char* message)
{
    std::cout << "Usage: " << message << "ip port" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(-1);
    }
    Sock sock;
    int sockfd = sock.Socket();
    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);
    sock.Connect(sockfd, port, ip);

    while(true)
    {
        Request req;

        std::cout << "请输入# ";
        std::cin >> req._x >> req._op >> req._y;

        // 序列化
        std::string s = req.Serialize();
        std::string package = Encode(s);
        Send(sockfd, package);
        // 反序列化
        std::string inbuffer;
        bool ret = Recv(sockfd, &inbuffer);
        if(!ret) continue;
        package = Decode(inbuffer);
        Response res;
        res.Deserialize(package);

        if(res._code == 1) std::cout << "code(" << res._code << "): 除0错误" << std::endl;
        else if(res._code == 2) std::cout << "code(" << res._code << "): 模0错误" << std::endl;
        else if(res._code == 3) std::cout << "code(" << res._code << "): 非法操作" << std::endl;
        else std::cout << "result: " << req._x << req._op << req._y << "=" << res._result << std::endl;
    }

    close(sockfd);
    return 0;
}